<?php
	
class ProducerDAL{
		
	private $m_databaseConnection;
	
	public function __construct (){
		try{
			//new connection
			$this->m_databaseConnection = new PDO('sqlite:UserDB.sqlite');
			$this->m_databaseConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		}catch(PDOException $e){
			die("Ett fel har inträffat: " . $e->getMessage());
		}
	}
	public function GetAllPositions(){
		try{
			$stmt = $this->m_databaseConnection->prepare("SELECT pID, longitude, latitude, description FROM POSITION");	
			$result = $stmt->execute();
		}	catch(exception $e){
			
		}
		
		if($result == true){
			//Returns next row as an array indexed by column name
			$result = $stmt->fetchAll(PDO::FETCH_ASSOC);//$stmt->fetch(PDO::FETCH_ASSOC);
			return $result;
		}else{
			return false;
		}
	}
	
	public function GetPositionById($a_pId){
		try{
			$stmt = $this->m_databaseConnection->prepare("SELECT pID, longitude, latitude, description FROM POSITION WHERE pID = ?");
			$stmt -> bindParam(1, $a_pId);
			$execute = $stmt->execute();
		
		}catch (exception $e){
			//Implement in future? 
		}
		
		if($execute){
		//Returns next row as an array indexed by column name
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		$formatResult[0] = $result;		
		if(!empty($result)){
			return $formatResult;	
		}else{
			return null;
		}
		}else{
			return false;
		}

	}
	
	public function CreatePosition($a_pId, $a_longitude, $a_latitude, $a_description){
		
		try{
			//Insert new Producer and position
			$stmt = $this->m_databaseConnection->prepare('
			INSERT INTO 
			POSITION (pID, longitude, latitude, description) 
			VALUES (?, ?, ?, ?)');
			
			$stmt->bindParam(1, $a_pId);
			$stmt->bindParam(2, $a_longitude);
			$stmt->bindParam(3, $a_latitude);
			$stmt->bindParam(4, $a_description);
			
			$result = $stmt->execute();
		}catch(exception $e){
			//Implement
		}

		if($result == true){		
			return true;	
		}else{
			return false;
		}
	}
	
	public function UpdatePosition($a_pId, $a_longitude, $a_latitude, $a_description){

		try{
			$stmt = $this->m_databaseConnection->prepare('UPDATE POSITION SET longitude = ?, latitude = ?, description = ? WHERE pID = ?');
		
			$stmt->bindParam(1, $a_longitude);
			$stmt->bindParam(2, $a_latitude);
			$stmt->bindParam(3, $a_description);
			$stmt->bindParam(4, $a_pId);
			$result = $stmt->execute();
		}catch(exception $e){
			//implement
		}
		
		if($result == 1){
			return true;			
			
		}elseif($result ==0){
			return null;
		}else{
			return false;
		}
	}
	
	public function DeletePosition($a_id){
		try{
			$stmt = $this->m_databaseConnection->prepare('DELETE FROM POSITION WHERE "pID" =?');		
		 	$stmt->bindParam(1, $a_id);
			$result = $stmt->execute();
			

		}catch(exception $e){
			//implement...
		}
		if($result == 1){		
			return true;
		}else{
			return false;
		}
	}	
}
